#!/Users/hepeng/.pyenv/shims/python
# -*- coding: utf-8 -*-
# @Time    : 2020/9/1 11:49 上午
# @Author  : hepeng
# @Site    : 
# @File    : BasePlugin.py

from __future__ import unicode_literals
import os, envoy
from utils.tools import cp_file, get_play_book_path
from utils.IniUtils import ConfigHanlder


class BasePlugin(object):
    def __init__(self, plugin_path, kwargs=None):
        if kwargs is None:
            kwargs = {}
        self._pug_path = plugin_path
        self._kwargs = kwargs

    @property
    def plugin_path(self):
        return self._pug_path

    def run(self):
        raise NotImplementedError


class FileCopyPlugin(BasePlugin):
    def __init__(self, plugin_path, kwargs):
        super(FileCopyPlugin, self).__init__(plugin_path, kwargs)

    def run(self):
        src_file = self._kwargs.get('src_file')
        dest_dir = self._kwargs.get('dest_dir')
        cp_file(src_file, dest_dir)


class UserPlugin(BasePlugin):
    def __init__(self, plugin_path, kwargs):
        super(UserPlugin, self).__init__(plugin_path, kwargs)

    def run(self):
        user = self._kwargs.get('user')
        group = self._kwargs.get('group')
        group_rep = envoy.run("egrep \"^%s\" /etc/group" %group)
        if group_rep.status_code !=0:
            add_group_rep = envoy.run('groupadd -r %s' %group)
            assert add_group_rep == 0
        response = envoy.run('id -u %s' %user)
        if not response.status_code == 0:
            add_u_rep = envoy.run('useradd -g mysql -s /sbin/nologin %s' %user)
            assert  add_u_rep.status_code == 0



class LoadPlugins(object):
    def __init__(self, playbook_name):
        self._pbn = playbook_name

    def get_plugins_with_index(self):
        pb_all_path = os.path.join(get_play_book_path(), self._pbn)
        if not os.path.exists(pb_all_path):
            raise ValueError('no found playbook : %s' % pb_all_path)
        conf_parse = ConfigHanlder(pb_all_path)
        plugins_dict = conf_parse.get_all_dict()
        sorted_keys = sorted(plugins_dict.keys(), key=lambda key: key.rsplit('_', 1))
        return {key: plugins_dict.get(key) for key in sorted_keys}

    def plugin_lanucher(self):
        plugins = self.get_plugins_with_index()
        if not plugins:
            raise ValueError('plugins dict is None')
        for k, v in plugins.items():
            instance = self.load_plugin(v.pop('plugin_path'), v)
            self.run_plugin(instance)

    def load_plugin(self, plugin_path, kwargs):
        moduleName, pluginClassName = plugin_path.rsplit(".", 1)
        module = __import__(moduleName, fromlist=[str(pluginClassName), ])
        pluginClass = getattr(module, pluginClassName)
        return pluginClass(plugin_path, kwargs)

    def run_plugin(self, plugin_clz):
        plugin_clz.run()


if __name__ == '__main__':
    lp = LoadPlugins('dev.ini')
    lp.plugin_lanucher()
